/**
 * 
 */
package com.attilax.web;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import org.apache.commons.lang3.StringUtils;

import com.attilax.coll.ListX;
import com.attilax.collection.listUtil;
import com.attilax.exception.ExUtil;
//import com.attilax.net.URLEncoder;  q426
import com.attilax.net.websitex;

/**
 * 
 * 
 * @author ASIMO
 *
 */
public class UrlX {

	/**
	 * @author attilax 老哇的爪子
	 * @throws IOException
	 * @since obb h_46_s
	 */
	public static void main(String[] args) throws IOException {
		// String
		// downloadUrl="http://211.147.235.199:8888/vod/uploadf/huangweicheng/music2.mp4";
		// downloadUrl="http://192.168.1.33/vod/uploadf/01.mp4";
		// int fileSize = getFileSize(downloadUrl);
		// System.out.println(fileSize);
		System.out.println(URLEncoder.encode("全国邮编区号搜索00", "gbk"));

		String file = "http://192.168.1.33:8080/vod/uploadf编码/1205.rmvb";
		System.out.println(UrlX.encodeURI(file));
		
		file="new(com.attilax.util.connReduceDync).set_resfile(uc_js.txt).joinNout()";
		String t_urlencode = URLEncoder.encode(file, "utf-8");
		String url = "http://localhost/vod/api.jsp?submethod=getFileSize&appid=1234507y767676&sign=xxxxxx&param="
				+ t_urlencode;
		System.out.println(t_urlencode);
	//	System.out.println(websitex.WebpageContent(url));
		;

	}

	/**
	attilax    2016年4月15日  下午5:52:03
	 * @param file
	 * @return
	 */
	private static String encodeURI(String url) {
		 String origin=getOrigin(url);
		 String origin_after=url.substring(origin.length()+1);
		 String[] a=origin_after.split("/");
		 List<String>  li=new ArrayList<String>();
		 for (String uri_part : a) {
			try {
				String part_encoded=URLEncoder.encode(uri_part, "utf8");
				li.add(part_encoded);
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		 
		String after_encoded=listUtil.join(li, "/");
		
	
		 
		 
		return origin+"/"+after_encoded;
	}
//	private static String deHostPart(String url) {
//		url = deProtocal(url);
//		url=deHost(url);
//		return  url;
//	}
	/**
	attilax    2016年4月15日  下午5:52:33
	 * @param url
	 * @return
	 */
	private static String getOrigin(String url) {
		char[] ca=url.toCharArray();
		int idx=0;
		int slashCount=0;
		for (char c : ca) {
			idx++;
			if(c=='/')
				slashCount++;
			if(slashCount==3)
				break;
		}
		return url.substring(0,idx-1);
	}

	public static Map<String, String> getHeader(String url) {
		Map<String, String> map = new TreeMap<String, String>();
		int start = url.indexOf("?");
		if (start >= 0) {
			String str = url.substring(start + 1);
			System.out.println(str);
			String[] paramsArr = str.split("&");
			for (String param : paramsArr) {
				String[] temp = param.split("=");
				map.put(temp[0], temp[1]);
			}
		}
		return map;
	}
	
	public static Map<String, String> getHeader_from_QueryStr(String url) {
		Map<String, String> map = new TreeMap<String, String>();
	 
	       if(url.contains("?"))
	    	   url=getQueryStr(url);
			String str = url;
			System.out.println(str);
			String[] paramsArr = str.split("&");
			for (String param : paramsArr) {
				String[] temp = param.split("=");
				//if(StringUtils.isNotEmpty(temp[1]))
				if(temp.length>=2)
				map.put(temp[0], temp[1]);
			}
		 
		return map;
	}

	public static String getQueryStr(Map map, String enc) {
		// Map<String, String> map = new TreeMap<String, String>();
		// int start = url.indexOf("?");
		// if (start >= 0) {
		// String str = url.substring(start + 1);
		// System.out.println(str);
		// String[] paramsArr = str.split("&");
		// for (String param : paramsArr) {
		// String[] temp = param.split("=");
		// map.put(temp[0], temp[1]);
		// }
		// }
		String s = "";
		Set<Map.Entry<String, Object>> set = map.entrySet();
		for (Iterator<Map.Entry<String, Object>> it = set.iterator(); it
				.hasNext();) {
			Map.Entry<String, Object> entry = (Map.Entry<String, Object>) it
					.next();
			if (s.equals(""))
				try {
					s = entry.getKey()
							+ "="
							+ URLEncoder.encode(entry.getValue().toString(),
									enc);
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			else
				try {
					s = s
							+ "&"
							+ entry.getKey()
							+ "="
							+ URLEncoder.encode(entry.getValue().toString(),
									enc);
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}
		return s;
	}

	public static long getFileSize(String downloadUrl)
			throws MalformedURLException, IOException, ProtocolException {
		URL url = new URL(downloadUrl);

		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setConnectTimeout(5 * 1000);
		// conn.setRequestProperty("Accept-Language", Params.ACCEPT_LANGUAGE);
		// conn.setRequestProperty("Charset", Params.ChARSET);
		conn.setRequestMethod("GET");
		int statusCode = conn.getResponseCode();
		if (statusCode != 200)
			throw new RuntimeException("httpstate:"
					+ String.valueOf(statusCode) + " url:" + downloadUrl);
		// if(conn)
		// conn.setRequestProperty("Connetion", "Keep-Alive");
		// 文件大小

		long fileSize = conn.getContentLengthLong();
		return fileSize;
	}
	
	
	
	public int port(String uRL) {
		// 分析可能存在的端口号
		
	String	host=host(uRL);
				int n;
				n = host.indexOf(':');
				if (n != -1) {
					int port = Integer.parseInt(host.substring(n + 1));
					return port;
				//	host = host.substring(0, n);
				}
				return 80;
	}

	public String hostNoport(String uRL) {
		// 分析可能存在的端口号
		String	host=host(uRL);
		int n;
		n = host.indexOf(':');
		if (n != -1) {
			//port = Integer.parseInt(host.substring(n + 1));
			host = host.substring(0, n);
		}
		return host;
	}

	public String getRequestURL(String buffer) {
		String[] tokens = buffer.split(" ");
		String URL = "";
		for (int index = 0; index < tokens.length; index++) {
			if (tokens[index].startsWith("http://")) {
				URL = tokens[index];
				break;
			}
		}
		return URL;
	}
	/**
	 * with port
	 * @param URL
	 * @return
	 */
	public String host(String URL) {
		 String host="";
		int n;
		// 抽取host
		n = URL.indexOf("//");
		if (n != -1)
			host = URL.substring(n + 2); // www.baidu.com/
		n = host.indexOf('/');
		if (n != -1)
			host = host.substring(0, n);// www.baidu.com
		return host;
	}
/**
 * 
 * @param url
 * @return
 */
	public static String getQueryStr(String url) {
		int idxStart=0;
		if(url.contains("?"))
		{
			idxStart=url.indexOf("?");
		}
		String queryStr=url.substring(idxStart+1);
		return queryStr;
	}

public static String decode(String uri) {
	try {
		return	 URLDecoder.decode(uri, "utf8");
	} catch (UnsupportedEncodingException e) {
		ExUtil.throwExV2(e);
	}
	return uri;
	 
}

/**
attilax    2016年9月27日  下午4:15:38
 * @param artUrl
 * @return
 */
public static String getPath(String artUrl) {
	int n=artUrl.lastIndexOf("/");
	return artUrl.substring(0, n);
}

}
